package com.zhihaoliang.baseframe.ui;

import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;

import com.zhihaoliang.baseframe.R;
import com.zhihaoliang.baseframe.databinding.FragmentProductListBinding;
import com.zhihaoliang.baseframe.db.entity.ProductEntity;
import com.zhihaoliang.baseframe.viewmodel.ProductListViewModel;

import java.util.List;

/**
 * 创建日期：2020-02-26
 * 描述:产品列表的Fragment
 * 作者:支豪亮
 */
public class ProductListFragment extends Fragment {
    public static final String TAG = "ProductListFragment";

    private ProductAdapter mProductAdapter;

    private FragmentProductListBinding mBing;

    private final ProductClickCallback mProductClickCallback = product -> {
        if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
            ((MainActivity) requireActivity()).show(product);
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBing = DataBindingUtil.inflate(inflater, R.layout.fragment_product_list, container, false);

        mProductAdapter = new ProductAdapter(mProductClickCallback);
        mBing.productsList.setAdapter(mProductAdapter);

        return mBing.getRoot();
    }

    @NonNull
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ProductListViewModel viewModel = new ViewModelProvider(this).get(ProductListViewModel.class);
        mBing.productSearchBtn.setOnClickListener(v -> {
            Editable query = mBing.productSearchBox.getText();
            viewModel.setQuery(query);
        });

        subsrcibeUI(viewModel.getmProducts());
    }

    private void subsrcibeUI(LiveData<List<ProductEntity>> liveData){
        liveData.observe(getViewLifecycleOwner(),products->{
            if(products == null){
                mBing.setIsLoading(true);
            }else{
                mBing.setIsLoading(false);
                mProductAdapter.setProductList(products);
            }
            //强制已经绑定数据的View立即更新
            mBing.executePendingBindings();
        });
    }

    @Override
    public void onDestroyView() {
        mBing = null;
        mProductAdapter = null;
        super.onDestroyView();
    }


}
